import 'dart:io';
import 'package:book_manager_app/app/modules/login/request/user_request.dart';
import 'package:book_manager_app/app/utils/app_version_manager/app_version_manager.dart';
import 'package:book_manager_app/app/utils/widget/common.dart';
import 'package:book_manager_app/host.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter_downloader/flutter_downloader.dart';
import 'package:get/get.dart';
import 'package:http_manager/http_manager.dart';

import '../pay_manager/wechat_pay/wechat_manager.dart';
import 'app_manager.dart';
import 'const.dart';
import 'result_code.dart';

class AppLaunching {

  // 启动
  static Future launching() async {
    await AppManager.getDeviceInfo();  // 确保首先执行这一步
    await AppVersionManager.init();
    await AppLaunching._setupNetwork();
    // await AppLaunching.requestPopAdvert();
    // await AppLaunching.requestActiveAdvert();
    await AppLaunching.requestUserToken();

    debugPrint("appLaunching()执行完毕");

    // WechatManager.instance.register();

    // UmengPushManager.initRegister();
    // debugPrint("UmengSDK 注册完毕!");
    // debugPrint("deviceToken:${await UmengPushManager.getDeviceToken()}");

    // if (!FlutterDownloader.initialized) {
    //   FlutterDownloader.initialize(debug: true, ignoreSsl: true);
    // }
  }

  // 配置网络
  static _setupNetwork() async {
    final debug = localStorageRead("isDebugBaseUrl")??false;
    HttpManager.baseUrl = debug == true ? baseURLTest : baseURL;
    final sid = AppManager.shopInfo?.shopId;
    final headers = {
      "User-Agent": "AutoSteward/${AppVersionManager.version}(iOS)",
    };
    if (AppManager.userToken != null) {
      headers["Authorization"] = "Bearer ${AppManager.userToken}";
    }
    HttpManager.setHeaders(headers);
    // HttpManager.setBaseParam({"shopInfoId": sid, "shopId": sid});
    ResponseAnalyzed.setResponseKey("code", "msg", "data");
    ResponseAnalyzed.setResultCheck((result) => ResponseAnalyzedExtention.checkeAnalyzing(result));
    
    debugPrint("setupNetwork() 执行完毕！HttpManager.baseUrl = ${HttpManager.baseUrl}");
    if (debug == true) {
      AfterDelay.milliseconds(3000, callBack: ()=> showMessage("请注意！当前为测试环境！"));
    }
  }




  static changeNetworkBaseURL({String? host}) {
    if (host != null) {
      localStorageWrite("isDebugBaseUrl", true);
      if (host.startsWith("http") != true) host = "http://$host";
      HttpManager.baseUrl = host;
      showMessage("已连接 ${local_hosts[host]} 的主机");
      debugPrint('=====已连接${local_hosts[host]}的主机=====');
    } else {
      if (localStorageRead("isDebugBaseUrl") == true) {
        HttpManager.baseUrl = baseURL;
        localStorageWrite("isDebugBaseUrl", false);
        showMessage("已切换正式环境");
        debugPrint('=====已切换正式环境=====');
      } else {
        HttpManager.baseUrl = baseURLTest;
        localStorageWrite("isDebugBaseUrl", true);
        showMessage("已切换测试环境");
        debugPrint('=====已切换测试环境=====');
      }
    }
    AppLaunching.requestUserToken();
  }

  // 根据设备UDID获取token
  static Future<ResponseAnalyzed> requestUserToken() async {
    return await UserRequest.getUserToken(AppManager.uuid);
  }

  // 展示用户协议
  static void readUserInfoTap() async {
    if (AppManager.isFirstInstall == false) {
      return;
    }
    debugPrint("第一次安装App");
    debugPrint("开始展示隐私协议");
    showAlertDialog(
        title: "隐私政策",
        margin: const EdgeInsets.only(left: 30, right: 30),
        messageTextSpan: _textSpan1(),
        confirmText: "同意",
        confirm: () async {
          dismissAlertDialog();
          debugPrint("用户同意个人隐私协议");
          AppManager.isFirstInstall = false;
          await AppLaunching.launching();
          // await AppLaunching._setSignStateHttp();
        },
        cancel: () {
          dismissAlertDialog();
          showAlertDialog(
              title: "温馨提示",
              messageTextSpan: _textSpan2(),
              confirmText: "同意",
              confirm: () async {
                dismissAlertDialog();
                debugPrint("用户同意个人隐私协议");
                AppManager.isFirstInstall = false;
                await AppLaunching.launching();
                // await AppLaunching._setSignStateHttp();
              },
              cancelText: "不同意",
              cancel: () {
                debugPrint("用户不同意协议，App已退出");
                exit(0);
              });
        });
  }

  // 设置用户隐私协议的签名状态
  // static Future _setSignStateHttp() async {
  //   if (AppManager.uuid.isNotEmpty) {
  //     var result = await CommonRe.setSignState(AppManager.uuid);
  //     if (result.success) {
  //       debugPrint("用户同意个人隐私协议，已上传服务器！");
  //     }
  //   } else {
  //     debugPrint("上报用户隐私以阅读的签名名状态：uuid为空!");
  //   }
  // }

  static InlineSpan? _textSpan1() {

    String contentTopAndroid = "您点击【同意】,即表示您已阅读并同意以上条款。请您充分了解在使用本软件过程中我们可能收集、使用您的个人信息情形，"
        "希望您着重关注：\n"
        "1：为了消息推送，我们采用友盟SDK，采集您的设备（IMEI/MAC/Android ID/IDFA/OAID/OpenUDID/GUID/SIM卡IMSI/ICCID位置信息、网络信息等。\n"//
        "2: 在使用各模块的过程中，第三方SDK会处理设备MAC地址、软件安装列表、位置、联系人、通话记录、日历、短息本机电话号码、等信息。\n"//
        "APP内【设置-关于我们】有【隐私政策】的常驻入口，我们将全力保障您的合法权益与信息安全,并将持续为您提供更优质的服务。\n";//

    String contentTopIOS = '依据最新的监管要求更新了用户隐私保护协议，并且禁止软件获取不相关的权限和数据，以此来最大限度的保护用户的利益。为此我们明确了用户的查询、更正和删除其个人信息的方式。\n请仔细阅读';

    return TextSpan(children: [
      TextSpan(
        text: Platform.isIOS?contentTopIOS:contentTopAndroid,
        style: Platform.isIOS?const TextStyle(fontSize: 16, color: Colors.black, height: 1.5):const TextStyle(fontSize: 12.5, color: Colors.black, height: 1.3),
      ),
      TextSpan(
          text: '《服务协议》',
          style: Platform.isIOS?const TextStyle(fontSize: 16, color: Colors.blue, decorationColor: Colors.blue, height: 1.5):const TextStyle(fontSize: 12.5, color: Colors.blue, decorationColor: Colors.blue, height: 1.3),
          recognizer: TapGestureRecognizer()
            ..onTap = () {
              Get.toNamed("/WebViewPage", arguments: {
                "url": agreementUrl,
                "title": "服务协议",
              });
            }),
      TextSpan(
        text: '和',
        style: Platform.isIOS?const TextStyle(fontSize: 16, color: Colors.black, height: 1.5):const TextStyle(fontSize: 12.5, color: Colors.black, height: 1.3),
      ),
      TextSpan(
          text: '《隐私政策》',
          style: Platform.isIOS?const TextStyle(fontSize: 16, color: Colors.blue, decorationColor: Colors.blue, height: 1.5):const TextStyle(fontSize: 12.5, color: Colors.blue, decorationColor: Colors.blue, height: 1.3),
          recognizer: TapGestureRecognizer()
            ..onTap = () {
              Get.toNamed("/WebViewPage", arguments: {
                "url": privacyUrl,
                "title": "用户隐私政策",
              });
            }),
      TextSpan(
          text: '尤其是加粗和划横线的内容，并了解我们对您个人信息的处理规则。',
          style: Platform.isIOS?const TextStyle(fontSize: 16, color: Colors.black, height: 1.5):const TextStyle(fontSize: 12.5, color: Colors.black, height: 1.3)
      ),
    ]);
  }

  static InlineSpan? _textSpan2() {
    return TextSpan(children: [
      const TextSpan(
        text: '为了在提供服务的同时，更好的保障您的合法权益，请仔细阅读我们的',
        style: TextStyle(fontSize: 16, color: Colors.black, height: 1.5),
      ),
      TextSpan(
          text: '《服务协议》',
          style: const TextStyle(fontSize: 16, color: Colors.blue, decorationColor: Colors.blue, height: 1.5),
          recognizer: TapGestureRecognizer()
            ..onTap = () {
              Get.toNamed("/WebViewPage", arguments: {
                "url": "https://echelianhtml.ygxpt.com/agreement/index.html",
                "title": "服务协议",
              });
            }),
      const TextSpan(
        text: '和',
        style: TextStyle(fontSize: 16, color: Colors.black, height: 1.5),
      ),
      TextSpan(
          text: '《隐私政策》',
          style: const TextStyle(fontSize: 16, color: Colors.blue, decorationColor: Colors.blue, height: 1.5),
          recognizer: TapGestureRecognizer()
            ..onTap = () {
              Get.toNamed("/WebViewPage", arguments: {
                "url": "https://echelianhtml.ygxpt.com/privacy/index.html",
                "title": "用户隐私政策",
              });
            }),
      const TextSpan(
        text: '我们尊重您的选择，如果您不同意，我们无法为您提供相应的服务，App也将会退出。',
        style: TextStyle(fontSize: 16, color: Colors.black, height: 1.5),
      ),
    ]);
  }
}
